import { defineStore } from "pinia"
import { Tag } from "@/models/tag"
import { CoursePageSearch, CoursePageResult } from "@/models/course"
import { courseApi, tagApi } from "@/services"
import { toast } from "vue3-toastify"

const useAllCourseStore  = defineStore('AllCourse', {
    // state
    state:() =>({
        pageSize: 16,
        pageNum: 1,
        totalRecords: 0,
        coursePageResult: {} as CoursePageResult,
        tagList: [] as Tag[],
        checkedTagIds: [] as number[],
    }),
    // actions
    actions:{
        // 获取所有的课程列表（分页）
        async getAllCourses(tagIds:number[], pageSize:number, pageNum:number) {
            try{        
                const data : CoursePageSearch = {
                    tagList: tagIds,
                    pageSize: pageSize,
                    pageNum: pageNum,
                }
                const res = await courseApi.getCourses(data)
                this.checkedTagIds = tagIds
                this.pageSize = pageSize
                this.pageNum = pageNum
                this.coursePageResult = res
                this.totalRecords = this.coursePageResult.count             
            } catch(err) {
                toast.error('获取所有的课程列表出现异常：'+ err);
            }
        },

        // 获取课程Tag列表
        async getCourseTags() {
            try{
                const res = await tagApi.getCourseTags()
                this.tagList = res          
            } catch(err) {
                toast.error('获取课程Tag列表出现异常：'+ err);
            }
        },

        // 初始化数据
        async initData(){
            await this.getCourseTags();
            await this.refreshData();
        },

        // 刷新数据（在当前页）
        async refreshData(){
            await this.getAllCourses(this.checkedTagIds,this.pageSize,this.pageNum)
        },

        // 开始查询
        async handleSearch(){      
            await this.getAllCourses(this.checkedTagIds,this.pageSize,1)
        },

        async handlePageChange(pageNum:number,pageSize:number){     
            this.pageNum = pageNum
            this.pageSize = pageSize   
            this.refreshData()
        }
    },
    getters:{
        courseSource:(state) => state.coursePageResult.records,
        tagSource:(state) => state.tagList,
    }
})

export default useAllCourseStore